package edu.ynu.se.xiecheng.achitectureclass.service;


import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.SensorDao;
import edu.ynu.se.xiecheng.achitectureclass.dto.SensorDTO;
import edu.ynu.se.xiecheng.achitectureclass.entity.Sensor;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



import java.text.ParseException;
import java.util.stream.Collectors;


@Service
public class SensorService extends LogicService<SensorDao, Sensor, Long>  {

    public SensorService(@Autowired SensorDao sensorDao) {
        super(sensorDao);
    }

    List<Sensor> newData;

    public void getNewData() {
        String boxNo = "300822040454"; // 根据请求URL，这是大棚的boxNo
        String accessToken ="eyJhbGciOiJSUzI1NiIsImtpZCI6Ijg2QzQ2RTIxQTc0MTUxNTFCOTQ0MTY4MzhEMERGODU1OTZENkM2RTgiLCJ0eXAiOiJhdCtqd3QiLCJ4NXQiOiJoc1J1SWFkQlVWRzVSQmFEalEzNFZaYld4dWcifQ.eyJuYmYiOjE3MzUwNTE2NDAsImV4cCI6MTczNTA1ODg0MCwiaXNzIjoiaHR0cHM6Ly9hY2NvdW50LmZsZXhlbS5jb20vY29yZSIsImF1ZCI6Imlkc3ZyMyIsImNsaWVudF9pZCI6IjY4ZGIyZThiZGE4ZDQ3YjViNWRiN2VhZjcxYzdkY2RkIiwic3ViIjoiZTcxMjRhMTYtMjEwNS00ZTU4LWI5OGItOWE2ZmFkNjZiYjA3Iiwic2NvcGUiOlsiZmJveCJdfQ.g_9-2LcZ3JatghdymHwKDalqTdZx7wTo8bRXPInB9FoY47YFeGKKo78CgQl5OOQENc5ma1PVxBaNs3uMhCB9-JGtg4Tuy2sHBoIykyopWQMWqdsBgT7FIAwcPW4XbCT3LCpTllTOyc4oZxsSJT1scMFCN2npITOUvZy4MLPZxPbKhDqDcuSFqIa97Vy_A7-zUgZSbxTwtYNC7Q-0w45XgKilKmoUiDtD38sTSreLLU7O-bkcxblpA_vAKCFGXxe4UvYsE8t5iucczwLIcbRLOuaNa6GhSjkSG8apFqXUZUHhje_1DEsiIMEVb3ITaU794bBq5OajggMr5R3Ux3uqFg";

        // 构建请求体
        JSONObject requestBody = new JSONObject();
        JSONArray idsArray = new JSONArray();
        idsArray.put("327061586065758005");
        idsArray.put("327061586065758015");
        idsArray.put("327061586065758006");
        idsArray.put("327061586065758007");
        idsArray.put("327061586065758008");
        idsArray.put("327061586065758009");
        idsArray.put("327061586065758010");
        idsArray.put("327061586065758013");
        idsArray.put("327061586065758014");
        idsArray.put("327061586065758012");
        idsArray.put("327061586065758011");

        requestBody.put("ids", idsArray); // 使用JSONArray来构建数组

        // 创建HttpClient实例
        HttpClient client = HttpClient.newHttpClient();

        // 构建请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo)) // 正确地构建URI
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + accessToken) // 添加Authorization头
                .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString())) // 发送JSON请求体
                .build();

        // 发送请求并获取响应
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("response:"+response.body());
            // 打印响应状态码和响应体
//            System.out.println("Status Code: " + response.statusCode());

            // 解析响应体并封装成Sensor列表
            newData = parseSensors(response.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static List<Sensor> parseSensors(String responseBody) {
        List<Sensor> sensorList = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(responseBody);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject sensorJson = jsonArray.getJSONObject(i);
                Sensor sensor = new Sensor();

//                sensor.setId(sensorJson.getString("id"));
                sensor.setTimestamp(parseDate(sensorJson.getString("timestamp")));
                sensor.setDataType(sensorJson.getInt("dataType"));
                sensor.setName(sensorJson.getString("name"));
                sensor.setValue(sensorJson.getInt("value"));
                sensor.setBoxId(sensorJson.getString("boxId"));
                sensor.setStatus(sensorJson.getInt("status"));
                sensor.setConnState(sensorJson.getInt("connState"));
                sensor.setConnStateTimestamp(parseDate(sensorJson.getString("connStateTimestamp")));

                sensorList.add(sensor);
            }
        } catch (Exception e) {
//            System.out.println("Response is not a valid JSON array: " + e.getMessage());
            // 这里可以处理非JSON数组的情况，例如打印原始响应体或返回空列表
            return new ArrayList<>(); // 返回空列表
        }
        return sensorList;
    }

    private static Date parseDate(String dateStr) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        return dateFormat.parse(dateStr);
    }

    public Boolean refreshData() {
        try {
            getNewData();
            if (newData == null || newData.isEmpty()) {
                System.out.println("No new data to refresh.");
                return false;
            }
            getDAO().saveAll(newData);
            System.out.println("Data refresh successful.");
        } catch (Exception e) {
            System.err.println("Error refreshing data: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public List<SensorDTO> getAllSensorsDTO() {
        List<Sensor> sensors = getAll();
        return sensors.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    private SensorDTO convertToDTO(Sensor sensor) {
        SensorDTO sensorDTO = new SensorDTO();
        sensorDTO.setId(sensor.getId());
        sensorDTO.setTimestamp(sensor.getTimestamp());
        sensorDTO.setDataType(sensor.getDataType());
        sensorDTO.setName(sensor.getName());
        sensorDTO.setValue(sensor.getValue());
        sensorDTO.setBoxId(sensor.getBoxId());
        sensorDTO.setStatus(sensor.getStatus());
        sensorDTO.setConnState(sensor.getConnState());
        sensorDTO.setConnStateTimestamp(sensor.getConnStateTimestamp());
        return sensorDTO;
    }
}
